using System;
using ValidationFramework.Extensions;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using ValidationFramework.Reflection;

namespace ValidationFramework.Web.ASP
{
    public class CompareRuleClientValidationGenerator : IClientValidationGenerator
    {


        /// <inheritdoc />
        public IList<BaseValidator> CreateWebClientValidators(Rule rule, InfoDescriptor infoDescriptor)
        {

            var validationDataType = ValidatorCreatorHelper.GetValidationDataType(infoDescriptor.RuntimeTypeHandle);
            var compareOperator = (CompareOperator) rule.GetPropertyValue("CompareOperator");
            var webValidator = new CompareWebValidatorEx
                                   {
                                       Operator = ValidatorCreatorHelper.GetOperator(compareOperator),
                                       Type = validationDataType.Value
                                   };
            if (webValidator.Type == ValidationDataType.Date)
            {
                var initialValueAsDateTime = (DateTime) rule.GetPropertyValue("ValueToCompare");
                if (initialValueAsDateTime.TimeOfDay == TimeSpan.Zero)
                {
                    webValidator.ValueToCompare = initialValueAsDateTime.ToString("yyyy-MM-dd");
                }
                else
                {
                    return null;
                }
            }
            else
            {
                webValidator.ValueToCompare = rule.GetPropertyValue("ValueToCompare").ToString();
            }
            return new BaseValidator[] {webValidator};
        }


        /// <inheritdoc />
        public bool CanHandleTarget(RuleContext ruleContext)
        {

            var type = ruleContext.Rule.GetType();
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(CompareRule<>))
			{
                return ValidatorCreatorHelper.GetValidationDataType(ruleContext.InfoDescriptor.RuntimeTypeHandle) != null;
			}
        	return false;
        }
    }
}